package com.zhiqianbao.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.CouponInfo;
import com.zhiqianbao.mycoupon.AlreadyUsedConponFragment;
import com.zhiqianbao.mycoupon.BeOverdueConponFragment;
import com.zhiqianbao.mycoupon.NoUsedConponFragment;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;

import java.util.HashMap;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

/**
 * Created by hp on 2017/7/17.
 */
public class MyCouponActivity extends BaseActivity {
    Button buttonRuturn;
    TabLayout tabNav;
    ViewPager baseViewPager;
    LinearLayout useDataLayout;
    RelativeLayout noDataLayout;
    TextView couponDataMsg;

    PagerInfo mInfoList[];
    public String serviceType="";
    BaseViewPagerAdapter adapter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mycoupon);
        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    public void initView(){
         buttonRuturn=(Button)findViewById(R.id.button_ruturn);
         tabNav=(TabLayout)findViewById(R.id.tab_nav);
         baseViewPager=(ViewPager)findViewById(R.id.base_viewPager);
         useDataLayout=(LinearLayout)findViewById(R.id.use_data_layout);
         noDataLayout=(RelativeLayout)findViewById(R.id.no_data_layout);
         couponDataMsg=(TextView)findViewById(R.id.coupon_data_msg);
    }
    public void initData() {
        Intent intent=getIntent();
        serviceType=intent.getStringExtra("serviceType");
        buttonRuturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        userCouponList();
    }

    protected PagerInfo[] getPagers(CouponInfo.DataBean dataBean) {
        PagerInfo[] pagerInfos = new PagerInfo[3];
        pagerInfos[0] = new PagerInfo("未使用("+dataBean.getUnUseCount()+")",
                NoUsedConponFragment.class, null);
        pagerInfos[1] = new PagerInfo("使用记录("+dataBean.getIsUseCount()+")",
                AlreadyUsedConponFragment.class, null);
        pagerInfos[2] = new PagerInfo("已过期("+dataBean.getOverdueCount()+")",
                BeOverdueConponFragment.class, null);
        return pagerInfos;
    }

    protected PagerInfo[] getNoData() {
        PagerInfo[] pagerInfos = new PagerInfo[3];
        pagerInfos[0] = new PagerInfo("未使用("+0+")",
                NoUsedConponFragment.class, null);
        pagerInfos[1] = new PagerInfo("使用记录("+0+")",
                AlreadyUsedConponFragment.class, null);
        pagerInfos[2] = new PagerInfo("已过期("+0+")",
                BeOverdueConponFragment.class, null);
        return pagerInfos;
    }
    public static class PagerInfo {
        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        private String title;
        private Class<?> clx;
        private Bundle args;

        public PagerInfo(String title, Class<?> clx, Bundle args) {
            this.title = title;
            this.clx = clx;
            this.args = args;
        }
    }

    public void refreshTabLayoutTitle(CouponInfo.DataBean dataBean) {
        tabNav.getTabAt(0).setText("未使用("+dataBean.getUnUseCount()+")");
        tabNav.getTabAt(1).setText("使用记录("+dataBean.getIsUseCount()+")");
        tabNav.getTabAt(2).setText("已过期("+dataBean.getOverdueCount()+")");
    }
    public class BaseViewPagerAdapter extends FragmentPagerAdapter {
        private Fragment mCurFragment;

        public BaseViewPagerAdapter(FragmentManager fm, PagerInfo[] infoList) {
            super(fm);
            mInfoList = infoList;
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            super.setPrimaryItem(container, position, object);
            if (object instanceof Fragment) {
                mCurFragment = (Fragment) object;
            }
        }

        public Fragment getCurFragment() {
            return mCurFragment;
        }

        @Override
        public Fragment getItem(int position) {
            PagerInfo info = mInfoList[position];
            return Fragment.instantiate(getApplicationContext(), info.clx.getName(),
                    info.args);
        }

        @Override
        public int getCount() {
            return mInfoList.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mInfoList[position].title;
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }

    }

    public static final int DATA_FILED=0x123;
    public static final int DATA_SCUESSFUL=0x124;
    private Gson gson = new Gson();
    /**
     * （userId:用户编号；type：1,2,3分别表示未使用,已使用,已过期；
     *  serviceType=1表示更多里优惠券列表;serviceType=2表示还款时可用优惠券列表）
     */
    private void userCouponList(){
        showWaitDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                mapParams.put("type", "1");
                mapParams.put("serviceType",serviceType);
                mapParams.put("pageSize", "10");
                mapParams.put("pageNum", "1");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/activity/userCouponList",
                        mapParams, MyCouponActivity.this);
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FILED;
                } else {
                    message.what = DATA_SCUESSFUL;
                    CouponInfo data =gson.fromJson(result, CouponInfo.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();
    }

    Handler postHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_FILED:
                    closeWaitDialog();
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case DATA_SCUESSFUL:
                    CouponInfo response = (CouponInfo) msg.obj;
                    closeWaitDialog();
                    useDataLayout.setVisibility(View.VISIBLE);
                    noDataLayout.setVisibility(View.GONE);
                    if(response!=null) {
                        if (response.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            CouponInfo.DataBean dataBean=response.getData();
                            if(dataBean!=null){
                                adapter = new BaseViewPagerAdapter(
                                        getSupportFragmentManager(), getPagers(dataBean));
                                baseViewPager.setAdapter(adapter);
                                tabNav.setupWithViewPager(baseViewPager);
                                baseViewPager.setCurrentItem(0, true);
                            }

                        } else {
                            adapter = new BaseViewPagerAdapter(
                                    getSupportFragmentManager(), getNoData());
                            baseViewPager.setAdapter(adapter);
                            tabNav.setupWithViewPager(baseViewPager);
                            baseViewPager.setCurrentItem(0, true);
                        }
                    }
                    else{
                        adapter = new BaseViewPagerAdapter(
                                getSupportFragmentManager(), getNoData());
                        baseViewPager.setAdapter(adapter);
                        tabNav.setupWithViewPager(baseViewPager);
                        baseViewPager.setCurrentItem(0, true);
                    }
                    break;
            }
        }
    };
}
